import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message } from '@nbase/ui';
import { UserOutlined, LockOutlined } from '@nbase/ui/icons';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '~/stores/auth.store';
import type { LoginDto } from '~/services/auth.service';
import './index.css';

/**
 * 登录页面
 */
const Login: React.FC = () => {
  const navigate = useNavigate();
  const login = useAuthStore((state) => state.login);
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
  const [loading, setLoading] = useState(false);

  /**
   * 如果已登录，直接跳转到首页
   */
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  /**
   * 处理登录
   */
  const handleLogin = async (values: LoginDto) => {
    try {
      setLoading(true);
      await login(values);
      message.success('登录成功');
      navigate('/', { replace: true });
    } catch {
      // 错误已由 request.ts 统一处理
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Card className="login-card" title="Nbase 管理系统">
        <Form
          name="login"
          initialValues={{ username: 'admin', password: 'admin123' }}
          onFinish={handleLogin}
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              autoComplete="current-password"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div className="login-tips">
          <p>默认账号：admin</p>
          <p>默认密码：admin123</p>
        </div>
      </Card>
    </div>
  );
};

export default Login;

